package com.transsion.clouddemo.core.config

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.CheckBox
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.Spinner
import android.widget.TextView
import androidx.core.content.ContextCompat.getSystemService
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.transsion.cloud_client_sdk.CloudSDKManager
import com.transsion.clouddemo.CloudApplication
import com.transsion.clouddemo.CloudApplication.Companion.initCloudSdk
import com.transsion.clouddemo.MainActivity
import com.transsion.clouddemo.R
import com.transsion.clouddemo.core.Custom.CloudClickListener
import com.transsion.clouddemo.core.Custom.CopyLinkTextHelper
import com.transsion.clouddemo.core.Custom.TransIDManager
import com.transsion.clouddemo.core.Custom.utils.GsonUtils
import com.transsion.clouddemo.core.Custom.utils.SPUtils
import com.transsion.clouddemo.core.Custom.utils.ThreadUtils
import com.transsion.clouddemo.core.Custom.utils.ToastUtils
import com.transsion.lib_interface.ServiceFetcher
import com.transsion.palmsdk.PalmID
import com.transsion.widgetslib.dialog.PromptDialog
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import kotlin.coroutines.coroutineContext

class ConfigFragment : Fragment() {


    private lateinit var mBinding: View
    private lateinit var sceneSelector: Spinner
    private lateinit var warn: TextView
    private lateinit var addScene: TextView
    private lateinit var sceneInputId: EditText
    private lateinit var sceneInputName: EditText
    private lateinit var sceneButtonSave: TextView
    private lateinit var textEnv: TextView
    private lateinit var onlineEnv: TextView
    private lateinit var currentEnv: TextView
    private lateinit var lastEnvTime: TextView
    private lateinit var uploadConcurrence: CheckBox
    private lateinit var concurrenceCountInput: EditText
    private lateinit var checkboxThreadPool: CheckBox
    private lateinit var threadCountInput: EditText
    private lateinit var buttonCopyLog: ImageView
    private lateinit var buttonCopyLogCurrent: ImageView
    private lateinit var buttonDeleteLogCurrent: ImageView

    private lateinit var addBusiness: LinearLayout
    private lateinit var envWarn: TextView
    private lateinit var threadPoolWarn: TextView
    private lateinit var concurrenceWarn: TextView
    private lateinit var concurrenceUploadLayout: LinearLayout
    private lateinit var customThreadPoolLayout: LinearLayout
    private lateinit var codeInfo: TextView
    private lateinit var logPath: TextView

    private lateinit var sceneInput: EditText


    //    private var isOnnDestroyed = false
    private lateinit var idDataList: MutableList<String>
    private lateinit var nameDataList: MutableList<String>
    private lateinit var sceneDataList: MutableList<String>


    private lateinit var adapter: ArrayAdapter<String>

    private lateinit var logRecyclerView: RecyclerView

    private lateinit var mServiceFetcher: ServiceFetcher

    companion object {

        const val TAG = "zhangxin"
        const val KEY_APP_ID = "appIds"
        const val KEY_SCENES_NAME = "scenesName"
        const val KEY_SCENES_SCENE = "scenes"
        const val KEY_ENV = "cloud_env"


        fun newInstance(): ConfigFragment {
            return ConfigFragment()
        }
    }

    fun setServiceFetcher(serviceFetcher: ServiceFetcher) {
        this.mServiceFetcher = serviceFetcher
    }


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        Log.e(TAG, "onCreateView")
        mBinding = inflater.inflate(R.layout.cloud_config, container, false)

        //初始化视图
        initView()
        //初始化SpinnerAdapter
        initSpinnerAdapter()
        //初始化新增业务场景按钮
        initAddSceneButton()
        //初始化新增业务保存按钮
        initSceneButtonSave()
        //初始化切换环境按钮
        initEnvButton()
        //初始化并发上传and自定义线程池的按钮
        initCheckBox()
        //初始化实时日志
        observeData()
        initCurrentLog()

        //初始化日志路径 (要放后面)
        initLogPath()





        return mBinding
    }


    fun initView() {
        Log.e(TAG, "initView")
        sceneSelector = mBinding.findViewById(R.id.scene_selector)
        warn = mBinding.findViewById(R.id.scene_selector_warning)
        warn.visibility = View.GONE

        addScene = mBinding.findViewById(R.id.scene_add)
        sceneInputId = mBinding.findViewById(R.id.scene_input_id)
        sceneInputName = mBinding.findViewById(R.id.scene_input_name)

        sceneButtonSave = mBinding.findViewById(R.id.scene_button_save)
        textEnv = mBinding.findViewById(R.id.button_env_test)
        onlineEnv = mBinding.findViewById(R.id.button_env_release)
        addBusiness = mBinding.findViewById(R.id.add_business)
        currentEnv = mBinding.findViewById(R.id.current_env)
        lastEnvTime = mBinding.findViewById(R.id.last_env_time)
        lastEnvTime.visibility = View.GONE
        envWarn = mBinding.findViewById(R.id.env_warn)
        envWarn.visibility = View.GONE

        threadPoolWarn = mBinding.findViewById(R.id.thread_pool_warn)
        concurrenceWarn = mBinding.findViewById(R.id.concurrence_warn)
        sceneInput=mBinding.findViewById(R.id.scene_input)

        //根据上次选择来初始化
        Log.e("zhangxin", "enc:${SPUtils.getString(KEY_ENV)!!}")
        if (SPUtils.getString(KEY_ENV).equals("test")) {
            textEnv.setTextColor(requireContext().getColor(R.color.cloud_text_selected))
            currentEnv.text = requireContext().getString(R.string.cloud_config_env_test)
        } else {
            onlineEnv.setTextColor(requireContext().getColor(R.color.cloud_text_selected))
            currentEnv.text = requireContext().getString(R.string.cloud_config_env_release)
        }

        uploadConcurrence = mBinding.findViewById(R.id.checkbox_concurrence)
        concurrenceCountInput = mBinding.findViewById(R.id.concurrence_count_input)
        checkboxThreadPool = mBinding.findViewById(R.id.checkbox_thread_pool)
        threadCountInput = mBinding.findViewById(R.id.thread_count_input)
        concurrenceUploadLayout = mBinding.findViewById(R.id.concurrence_upload_layout)
        customThreadPoolLayout = mBinding.findViewById(R.id.custom_thread_pool_layout)

        buttonCopyLog = mBinding.findViewById(R.id.button_copy_log)
        buttonCopyLogCurrent = mBinding.findViewById(R.id.button_copy_log_current)
        buttonDeleteLogCurrent = mBinding.findViewById(R.id.button_delete_log_current)

//        codeInfo = mBinding.findViewById(R.id.code_info)
        logPath = mBinding.findViewById(R.id.log_path)
//        currentLog = mBinding.findViewById(R.id.current_log)
        logRecyclerView = mBinding.findViewById(R.id.log_recycler_view)
        logRecyclerView.setBackgroundColor(Color.BLACK) // 使用Color类设置颜色


    }


    fun initSpinnerAdapter() {
        // 创建 ArrayAdapter
        idDataList = SPUtils.getString(KEY_APP_ID)
            ?.let { json -> GsonUtils.jsonToObject<MutableList<String>>(json) }!!
        nameDataList = SPUtils.getString(KEY_SCENES_NAME)
            ?.let { json -> GsonUtils.jsonToObject<MutableList<String>>(json) }!!
        sceneDataList = SPUtils.getString(KEY_SCENES_SCENE)
            ?.let { json -> GsonUtils.jsonToObject<MutableList<String>>(json) }!!

        adapter = context?.let {
            ArrayAdapter(
                it, // 上下文
                android.R.layout.simple_spinner_item, // 使用 Android 默认的简单布局
                // 数据源
                nameDataList
            )
        }!!

        // 设置下拉菜单的样式
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        // 绑定适配器到 Spinner
        sceneSelector.adapter = adapter

        // 初始化时选择第一个选项，并避免调用 onItemSelected
        sceneSelector.setSelection(0, false)




        sceneSelector.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                Log.e(TAG, "onItemSelectedListener")


                warn.visibility = View.VISIBLE
                warn.text = getString(R.string.cloud_config_scene_warning, nameDataList[position])

                //登录校验
                lifecycleScope.launch(Dispatchers.IO) { // 在IO调度器中启动协程
                    if (TransIDManager.queryTokenExpired()) {
                        Log.e(TAG,"token过期")
                        TransIDManager.refreshToken()
                    }
                    TransIDManager.authorize(requireActivity())
                }
                val checkLogin = CloudSDKManager.getInstance().checkLogin()
                Log.e(TAG, "checkLogin检查登录结果为： $checkLogin")

                initCloudSdk(idDataList[position], sceneDataList[position],CloudApplication.currentUseConcurrent,CloudApplication.currentUseThreadPool)
                CloudApplication.currentAppId = idDataList[position]
                CloudApplication.currentScene = sceneDataList[position]
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
            }

        }

    }

    fun initAddSceneButton() {
        addScene.setOnClickListener(object : CloudClickListener() {
            override fun onSingleClick(view: View) {

                addScene.visibility = View.GONE
                addBusiness.visibility = View.VISIBLE

            }

        })
    }

    fun initSceneButtonSave() {
        sceneButtonSave.setOnClickListener(object : CloudClickListener() {
            override fun onSingleClick(view: View) {
                val inputId = sceneInputId.text.toString()
                if (inputId.isEmpty()) {
                    context?.let {
                        ToastUtils.showShort(
                            it,
                            context!!.getString(R.string.cloud_input_warn)
                        )
                    }
                    return
                }
                val inputName = sceneInputName.text.toString()
                if (inputName.isEmpty()) {
                    context?.let {
                        ToastUtils.showShort(
                            it,
                            context!!.getString(R.string.cloud_input_warn)
                        )
                    }
                    return
                }
                val inputScene = sceneInput.text.toString()
                if (inputScene.isEmpty()) {
                    context?.let {
                        ToastUtils.showShort(
                            it,
                            context!!.getString(R.string.cloud_input_warn)
                        )
                    }
                    return
                }
                idDataList.add(inputId)
                nameDataList.add(inputName)
                sceneDataList.add(inputScene)

                updateDataInSP(idDataList,nameDataList,sceneDataList)
                addBusiness.visibility = View.GONE
                addScene.visibility = View.VISIBLE


            }
        })

    }

    fun updateDataInSP(idNewData: MutableList<String>,nameNewData: MutableList<String>,sceneNewData: MutableList<String>) {
        // 将新数据转换为JSON并存储到SP
        val idJson = GsonUtils.objectToJson(idNewData)
        val nameJson = GsonUtils.objectToJson(nameNewData)
        val sceneJson = GsonUtils.objectToJson(sceneNewData)


        SPUtils.putString(KEY_APP_ID, idJson)
        SPUtils.putString(KEY_SCENES_NAME, nameJson)
        SPUtils.putString(KEY_SCENES_SCENE, sceneJson)


        // 通知适配器数据已改变
        adapter.notifyDataSetChanged()
    }


    fun initEnvButton() {
        textEnv.setOnClickListener(object : CloudClickListener() {
            override fun onSingleClick(view: View) {
                if (SPUtils.getString(KEY_ENV).equals("test")) {
                    return
                }
                textEnv.setTextColor(context!!.getColor(R.color.cloud_text_selected))
                onlineEnv.setTextColor(context!!.getColor(R.color.cloud_text_default))
                currentEnv.text = context!!.getString(R.string.cloud_config_env_test)
                lastEnvTime.visibility = View.VISIBLE
                lastEnvTime.text =
                    getString(R.string.cloud_config_env_switch_last_time, getCurrentTime())
                envWarn.visibility = View.VISIBLE
                envWarn.text = getString(R.string.cloud_config_env_warning, currentEnv.text)

                //账号变为测试环境
                TransIDManager.logout(activity!!, PalmID.SERVER_TEST)
                //云服务切换为测试环境
//                sendSettingUpdateRequest("cloud_server_http_is_debug", -1)



                //初始化账号SDK并登录
//                TransIDManager.init(PalmID.SERVER_TEST)
//                lifecycleScope.launch(CoroutineExceptionHandler { _, exception ->
//                    Log.e(TAG, "切换环境命令出现异常")
//                    Log.e(TAG, exception.message!!)
//                    showLoginErrorDialog()
//                }) {
//                    val authorize = TransIDManager.authorize(requireActivity())
//                    Log.e("zhangxin", authorize)
//                }
//                SPUtils.putString(KEY_ENV, "test")
//                //初始化云服务SDK
//                initCloudSdk()
            }

        })

        onlineEnv.setOnClickListener(object : CloudClickListener() {
            override fun onSingleClick(view: View) {
                if (SPUtils.getString(KEY_ENV).equals("release")) {
                    return
                }
                textEnv.setTextColor(context!!.getColor(R.color.cloud_text_default))
                onlineEnv.setTextColor(context!!.getColor(R.color.cloud_text_selected))
                currentEnv.text = context!!.getString(R.string.cloud_config_env_release)
                lastEnvTime.visibility = View.VISIBLE
                lastEnvTime.text =
                    getString(R.string.cloud_config_env_switch_last_time, getCurrentTime())
                envWarn.visibility = View.VISIBLE
                envWarn.text = getString(R.string.cloud_config_env_warning, currentEnv.text)

                //账号变为线上环境
                TransIDManager.logout(activity!!, PalmID.SERVER_ONLINE)
                //云服务切换为线上环境
//                sendSettingUpdateRequest("cloud_server_http_is_debug", 1)


                //初始化账号SDK并登录
//                TransIDManager.init(PalmID.SERVER_ONLINE)
//                lifecycleScope.launch(CoroutineExceptionHandler { _, exception ->
//                    Log.e(TAG, "切换环境命令出现异常")
//                    Log.e(TAG, exception.message!!)
//                    showLoginErrorDialog()
//                }) {
//                    TransIDManager.authorize(requireActivity())
//                }
//                SPUtils.putString(KEY_ENV, "release")
//                //初始化云服务SDK
//                initCloudSdk()
            }

        })
    }






    fun initCheckBox() {
        uploadConcurrence.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) {
                // CheckBox被选中
                concurrenceWarn.visibility = View.VISIBLE
                concurrenceUploadLayout.visibility = View.VISIBLE
                initCloudSdk(CloudApplication.currentAppId,CloudApplication.currentScene,useConcurrent = true,CloudApplication.currentUseThreadPool)
                CloudApplication.currentUseConcurrent = true

            } else {
                // CheckBox被取消选中
                concurrenceWarn.visibility = View.GONE
                concurrenceUploadLayout.visibility = View.GONE
                initCloudSdk(CloudApplication.currentAppId,CloudApplication.currentScene,useConcurrent = false,CloudApplication.currentUseConcurrent)
                CloudApplication.currentUseConcurrent = false
            }
        }

        checkboxThreadPool.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) {
                // CheckBox被选中
                threadPoolWarn.visibility = View.VISIBLE
                customThreadPoolLayout.visibility = View.VISIBLE
                initCloudSdk(
                    CloudApplication.currentAppId,
                    CloudApplication.currentScene,
                    useConcurrent = false,
                    true
                )

            } else {
                // CheckBox被取消选中
                threadPoolWarn.visibility = View.GONE
                customThreadPoolLayout.visibility = View.GONE
                initCloudSdk(
                    CloudApplication.currentAppId,
                    CloudApplication.currentScene,
                    useConcurrent = false,
                    false
                )

            }
        }


        //下面进行输入后的事件监听

        //并发任务数
        concurrenceCountInput.setOnFocusChangeListener { _, hasFocus ->
            if (!hasFocus) {
                // EditText失去焦点时执行的逻辑
                val concurrenceCount = concurrenceCountInput.text.toString()  // 获取EditText中的文本
                if (concurrenceCount.isEmpty()) {
//                    ToastUtils.showShort(
//                        requireContext(),
//                        requireContext().getString(R.string.cloud_input_valid)
//                    )
                    hideKeyboard(requireContext(),concurrenceCountInput )

                    return@setOnFocusChangeListener
                }
                var count = 0
                try {
                    count = concurrenceCount.toIntOrNull()!!  // 尝试将输入的文本转换为整数
                } catch (e: NumberFormatException) {
                    // 如果转换失败，捕获异常并显示Toast提示
                    ToastUtils.showShort(requireContext(), "请输入有效的数字")
                }
                // 设置并发任务数
                ThreadUtils.adjustConcurrencyLimit(count)
                hideKeyboard(requireContext(),concurrenceCountInput )
                Log.e(TAG,"已经设置并发任务数为： $count")
            }
        }

        //自定义线程数
        threadCountInput.setOnFocusChangeListener { _, hasFocus ->
            if (!hasFocus) {
                // EditText失去焦点时执行的逻辑
                val threadCountInputString = threadCountInput.text.toString()  // 获取EditText中的文本
                if (threadCountInputString.isEmpty()) {
//                    ToastUtils.showShort(
//                        requireContext(),
//                        requireContext().getString(R.string.cloud_input_valid)
//                    )
                    hideKeyboard(requireContext(),threadCountInput )
                    return@setOnFocusChangeListener
                }
                var count = 0
                try {
                    count = threadCountInputString.toIntOrNull()!!  // 尝试将输入的文本转换为整数
                } catch (e: NumberFormatException) {
                    // 如果转换失败，捕获异常并显示Toast提示
                    ToastUtils.showShort(
                        requireContext(),
                        requireContext().getString(R.string.cloud_input_valid)
                    )
                }
                // 设置自定义线程数
                ThreadUtils.adjustThreadPoolSize(count)
                hideKeyboard(requireContext(),threadCountInput )
            }
        }
    }

    /**
     * 隐藏键盘
     */
    fun hideKeyboard(context: Context, view: View?) {
        // 获取输入法管理器服务
        val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        // 如果当前有焦点的视图存在
        if (view != null) {
            // 隐藏键盘
            inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
            // 清除视图的焦点
            view.clearFocus()
        }
    }

    fun initLogPath() {

        val path = logFile?.path
        logPath.text = getString(R.string.cloud_config_log_path, path)

        //日志路径复制
        buttonCopyLog.setOnClickListener(object : CloudClickListener() {
            override fun onSingleClick(view: View) {
                context?.let { CopyLinkTextHelper.getInstance(it)?.copyUrl(path) }
            }

        })
    }


    //实时日志
    fun initCurrentLog() {

        logFile = File(requireContext().filesDir, "logcat.txt")  // 定义用于存储日志的文件
        if (!logFile!!.exists()) {
            logFile!!.createNewFile()
        } else {
            logFile!!.writeText("")  // 清空文件内容
        }

        // 启动协程读取log
//        CoroutineScope(Dispatchers.IO).launch {
//            readLogcatAndWriteToFile()
//        }

        buttonCopyLogCurrent.setOnClickListener(object : CloudClickListener() {
            override fun onSingleClick(view: View) {
                val concatenatedMessages = logList.joinToString(separator = "\n") { it.message }
                context?.let {
                    CopyLinkTextHelper.getInstance(it)?.copyUrl(concatenatedMessages)
                }
//                context?.let { ToastUtils.showShort(it,"成功清除文件") }
                Log.e(TAG,"拷贝成功")
            }
        })

        buttonDeleteLogCurrent.setOnClickListener(object : CloudClickListener() {
            @SuppressLint("NotifyDataSetChanged")
            override fun onSingleClick(view: View) {
                logList.clear()
                mLogAdapter?.notifyDataSetChanged()
                context?.let { ToastUtils.showShort(it,"成功清除日志") }
            }
        })

    }

    fun sendSettingUpdateRequest(key: String, value: Int) {
        try {
            val intent = Intent("com.transsion.EnvSettingReceiver.UPDATE_ENV_SETTING")
            intent.putExtra("key", key)
            intent.putExtra("mode", value)
            intent.setPackage("com.transsion.cloudserver")
            context?.sendBroadcast(intent)
        } catch (e: Exception) {
            Log.e("zhangxin", "切换云服务环境出现异常： ${e.message}")
        }
    }



    //实时日志
    private var logFile: File? = null
    private val maxBufferLogLines = 1 // 放入日志的最大缓冲行数
    private val maxBufferLogShowLines = 500 // 放入日志的最大缓冲行数
    private val maxBufferFileLogLines = 30 // 写入日志文件的最大缓冲行数
    private val maxLogEntriesSize = 1000 // 最大日志行数
//    private val logEntries = mutableListOf<LogEntry>()


    //读取日志放到viewmodel的添加model中 并输入到日志文件中
    private suspend fun readLogcatAndWriteToFile() {
        try {
            val processId = android.os.Process.myPid().toString()
            Log.e(TAG, "processId: $processId")

            val process = withContext(Dispatchers.IO) {
                Runtime.getRuntime().exec("logcat okhttp:* zhangxin:* *:S")
            }
//            BufferedReader(InputStreamReader(process.inputStream)).use { bufferedReader ->
////                BufferedWriter(FileWriter(logFile, true)).use { writer ->
//                    var line: String?
//                    val bufferLogEntry = mutableListOf<LogEntry>()
////                    val bufferFileLogEntry = mutableListOf<String>()
//
//                    while (bufferedReader.readLine().also { line = it } != null) {
//                        line?.let {
//                            Log.e("zhangxin", "line: $line")
//                                bufferLogEntry.add(LogEntry(it))
////                                bufferFileLogEntry.add(it)
//                                //放入viewmodel
////                                if (bufferLogEntry.size >= maxBufferLogLines) {
//                                    logViewModel.updateLogEntries(bufferLogEntry)
//                                    bufferLogEntry.clear()
////                                }
////                            }
////                            //放入日志文件
////                            if (bufferFileLogEntry.size >= maxBufferFileLogLines) {
////                                writer.append(bufferFileLogEntry.joinToString(separator = "\n"))
////                                bufferFileLogEntry.clear()
////                            }
////                        }
//                    }
//                }
//            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private var logList = mutableListOf<LogEntry>()

    // ViewModel 初始化
    val logViewModel: LogViewModel by viewModels()
    // 用于控制自动滚动的标志
    var shouldAutoScroll = true

    var mLogAdapter: LogAdapter? = null


    @SuppressLint("NotifyDataSetChanged")
    fun observeData() {
        initLogRecyclerView()
        mLogAdapter = LogAdapter(logList)
        logRecyclerView.apply {
            layoutManager = LinearLayoutManager(context) // 线性布局管理器
            adapter = mLogAdapter // 设置适配器
        }

        // 观察 LiveData 并更新 UI
        logViewModel.addLogEntries.observe(viewLifecycleOwner, Observer {
            try {
                logList.addAll(it)
                if (shouldAutoScroll) {
                    logRecyclerView.scrollToPosition(logList.size - 1) // 滚动到列表底部
                }
                if (logList.size >= maxLogEntriesSize) {
                    logList =
                        logList.filterIndexed { index, _ -> index >= maxBufferLogShowLines }.toMutableList()
                }
                mLogAdapter?.notifyDataSetChanged()
            } catch (e: Exception) {
                Log.e(TAG, "添加日志出现异常： ${e.message}")
            }
        })
    }

    @SuppressLint("ClickableViewAccessibility")
    fun initLogRecyclerView() {
        // 设置一个触摸监听器来拦截滑动事件
        logRecyclerView.setOnTouchListener { v, event ->
            // 检查事件类型是否为 ACTION_MOVE
            if (event.action == MotionEvent.ACTION_MOVE) {
                // 请求父视图不要拦截触摸事件
                v.parent.requestDisallowInterceptTouchEvent(true)
            }
            // 返回 false 以允许 RecyclerView 继续处理触摸事件
            false
        }
        // 设置 RecyclerView 的滚动监听器
        logRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                    // 用户开始滚动，停止自动滚动
                    shouldAutoScroll = false
                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                if (!recyclerView.canScrollVertically(1)) {
                    // 用户滚动到达底部，恢复自动滚动
                    shouldAutoScroll = true
                }
            }
        })
    }


//    private suspend fun displayLogsFromFile() = coroutineScope {
//
//
//        while (isActive) {
//            withContext(Dispatchers.IO) {
//                val allLines = logFile?.readLines()  // 读取文件中所有行
//                val displayLines = if (allLines!!.size > maxLogLines) {
//                    allLines.takeLast(maxLogLines)  // 仅保留最新的maxLogLines行
//                } else {
//                    allLines
//                }
//                withContext(Dispatchers.Main) {
//                    currentLog.text = displayLines.joinToString("\n")  // 更新UI
//                }
//            }
//            delay(1000)  // 每隔1秒更新一次
//        }
//    }


    override fun onDestroyView() {
        super.onDestroyView()
        Log.e(TAG, "ConfigFragment-onDestroyView")
//        isOnnDestroyed = true
        envWarn.visibility = View.GONE
        lastEnvTime.visibility = View.GONE

    }

    fun clearScenes() {
        SPUtils.clearAll()
    }

    fun getCurrentTime(): String {
        val currentDateTime = LocalDateTime.now()  // 获取当前的日期和时间
        val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")  // 定义日期时间格式
        return currentDateTime.format(formatter)  // 格式化当前日期时间并返回
    }

    fun executeCommand(command: String): String {
        return try {
            val process = Runtime.getRuntime().exec(command)
            val result = process.inputStream.bufferedReader().readText()
            process.waitFor() // 等待进程执行完毕
            result
        } catch (e: Exception) {
            e.printStackTrace()
            "Error: ${e.message}"
        }
    }

    var mTimeDialog: PromptDialog? = null

    fun showLoginErrorDialog() {
        mTimeDialog = PromptDialog.Builder(requireActivity())
            .setTitle(R.string.app_name)
            .setMessage(R.string.cloud_relogin_message)
            .setPositiveButton(R.string.cloud_login_positive) { _, _ ->
                val intent=Intent(requireActivity(),MainActivity::class.java).apply {
                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
                }
                startActivity(intent)
            }
            .setCanceledOnTouchOutside(false)
            .setNegativeButton(R.string.cloud_login_cancel) { _, _ ->
                activity?.finish()
            }
            .show()
    }



}